
class InputDate < Widget
  attr_accessor :day, :month, :year
  attr_accessor :date
  attr_accessor :day_field, :month_field, :year_field

  def initialize(options)
    super()
    element.tag_name = 'span'

    self << @day_field = el(:select, :name => options[:name]+"_day")
    @day_field.options = (1..31).to_a

    self << @month_field = el(:select, :name => options[:name]+"_month")
    @month_field.options = (1..12).to_a

    self << @year_field = el(:select, :name => options[:name]+"_year")
    @year_field.options = (1990..2020).to_a
  end

  def date= date
#    if date.is_a? String
#      date = Date.parse(date)
#    end
    if date
      @day_field.value = date.day
      @month_field.value = date.month
      @year_field.value = date.year
    else
#      @day_field.value = nil
#      @month_field.value = nil
#      @year_field.value = nil
    end
  end

#  def recieve data
#    super
##    raise 'no year set' unless @year_field.value
##    raise 'no month set' unless @month_field.value
##    raise 'no day set' unless @day_field.value
#  end

  def date
    if @year_field.value
      Date.civil(
        @year_field.value,
        @month_field.value,
        @day_field.value
      )
    else
      nil
    end
  end

  class Test <FwTest
    def test_set_correct_values_to_selects
      i = InputDate.new :name => 'date'
      today = Date.today
      i.date = today

      eq i.year_field.value, today.year
      eq i.month_field.value, today.month
      eq i.day_field.value, today.day
    end

    def test_recieve_assembles_correct_date
      i = InputDate.new :name => 'date'
      today = Date.today
      i.date = today

      i2 = InputDate.new :name => 'date'
      i2.recieve(i.dump)
      eq i2.date, today
    end
  end
end